#include<iostream>
#include<string>
#include<pthread.h>
#include<cstdio>
#include<unistd.h>
using namespace std;

//多线程实现APP抢票逻辑


//一千张票
int tickets = 1000;//临界资源，共享资源

pthread_mutex_t mutex;

void* thread_run(void* argv)
{
    //线程进入后开始抢票
    //加锁
    pthread_mutex_lock(&mutex);
 
    while(true)
    {
        //临界区
        if(tickets>0)
        {
            cout<< static_cast<const char*>(argv) << tickets-- << endl;
            //不解锁会导致只要该线程被唤醒，那么该线程会一直拥有锁，其他线程无法运行
            pthread_mutex_unlock(&mutex);
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
        usleep(1000);
    }

    return nullptr;
}

int main()
{
    pthread_t tid[4];

    //4个线程
    for(int i =0;i<4;i++)
    {
        char* buf = new char[64];
        snprintf(buf,64,"thread_%d: ",i);
        pthread_create(&tid[i],nullptr,thread_run,(void*)buf);
    }

    for (int i = 0; i<4;i++)
    {
        pthread_join(tid[i],nullptr);
    }

    return 0;
}